<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon :closable="false"></el-alert>

      <el-row>
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader
            expand-trigger="hover"
            :options="patInfo"
            @change="patChange"
            :props="patProps"
            :change-on-select="true"
            v-model="selectedPat"
            :clearable="true"
          ></el-cascader>
        </el-col>
      </el-row>

      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" size="mini" :disabled="isDisabled" @click="showAddDialog">添加参数</el-button>

          <el-table :data="paramsManyInfo" border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  :key="tag+''+Math.random()"
                  v-for="tag in scope.row.attr_vals"
                  closable
                  :disable-transitions="true"
                  @close="handleClose(scope.row,tag)"
                >{{tag}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="inputVisible"
                  v-model="inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="序号"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini">修改</el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" size="mini" :disabled="isDisabled" @click="showAddDialog">添加属性</el-button>

          <el-table :data="paramsOnlyInfo" border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  :key="tag+''+Math.random()"
                  v-for="tag in scope.row.attr_vals"
                  closable
                  :disable-transitions="true"
                  @close="handleClose(scope.row,tag)"
                >{{tag}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="inputVisible"
                  v-model="inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="序号"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini">搜索</el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <el-dialog
        :title="'添加'+(activeName==='many'?'动态参数':'静态属性')"
        :visible.sync="addDialogVisible"
        width="50%"
        @close="addDialogClosed"
      >
        <el-form ref="addFormRef" :model="addForm" label-width="80px" :rules="addFormRules">
          <el-form-item label="参数名称" prop="attr_name">
            <el-input v-model="addForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addParam">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      /** 商品分类1 */
      patInfo: [],
      selectedPat: [],
      patProps: {
        label: 'cat_name',
        value: 'cat_id',
        // 设置了该children属性，鼠标滑过第一级别信息就可以把其直接填充到表单域里边
        children: 'children'
      },
      /** 商品分类2 */
      activeName: 'many',
      paramsManyInfo: [],
      paramsOnlyInfo: [],
      threeCatId: 0,

      /** 添加参数1 */
      addDialogVisible: false,
      addForm: {
        attr_name: ''
      },
      addFormRules: {
        attr_name: [
          {
            required: true,
            message: '请输入用户名称',
            trigger: 'blur'
          }
        ]
      },
      /** 添加参数2 */

      /** 参数可选项目相关1 */
      paramTags: [],
      inputVisible: false,
      inputValue: ''
      /** 参数可选项目相关2 */
    }
  },
  created() {
    this.getCatInfo()
    // this.threeCatId = catId
  },
  methods: {
    /** 参数可选项目相关1 */
    showInput() {
      this.inputVisible = true
      // console.log(this)
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 参数tag输入框失去焦点 或 点击回车键 的回调
    async handleInputConfirm(nowParam) {
      var newparam = this.inputValue.trim()
      if (newparam.length === 0) {
        this.inputVisible = false
        this.inputValue = ''
        return null
      }

      nowParam.attr_vals.push(newparam)
      this.inputVisible = false
      this.inputValue = ''

      // 提交存储分类参数
      var attrVals = nowParam.attr_vals.join(' ')
      const { data: res } = await this.$http.put(
        `categories/${this.threeCatId}/attributes/${nowParam.attr_id}`,
        {
          attr_name: nowParam.attr_name,
          attr_sel: this.activeName,
          attr_vals: attrVals
        }
      )

      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
    },
    // 删除tag参数可选项目
    async handleClose(nowParam, item) {
      nowParam.attr_vals.splice(nowParam.attr_vals.indexOf(item), 1)

      // 提交存储分类参数
      var attrVals = nowParam.attr_vals.join(' ')
      const { data: res } = await this.$http.put(
        `categories/${this.threeCatId}/attributes/${nowParam.attr_id}`,
        {
          attr_name: nowParam.attr_name,
          attr_sel: this.activeName,
          attr_vals: attrVals
        }
      )

      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
    },
    /** 参数可选项目相关2 */

    /** 添加参数1 */
    showAddDialog() {
      this.addDialogVisible = true
    },
    addDialogClosed() {
      this.addDialogVisible = false
      this.$refs.addFormRef.resetFields()
    },
    addParam() {
      this.$refs.addFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.post(
            `categories/${this.threeCatId}/attributes`,
            { attr_name: this.addForm.attr_name, attr_sel: this.activeName }
          )

          if (res.meta.status !== 201) {
            return this.$message.error(res.meta.msg)
          }

          this.getParamsByCatAndType()
          this.addDialogClosed()
          this.$message.success(res.meta.msg)
        }
      })
    },
    /** 添加参数2 */

    async getCatInfo() {
      // 获取可供选取的父级分类信息
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取上级分类数据失败！')
      }
      this.patInfo = res.data
    },
    // 商品分类变化后的回调
    patChange() {
      if (this.selectedPat.length === 3) {
        this.threeCatId = this.selectedPat[2]
        // 获取对应的参数信息
        this.getParamsByCatAndType()
      } else {
        this.paramsManyInfo = []
        this.paramsOnlyInfo = []
        this.selectedPat = []
        this.threeCatId = 0
      }
    },
    handleClick() {
      if (this.selectedPat.length === 3) {
        this.threeCatId = this.selectedPat[2]
        // 获取对应的参数信息
        this.getParamsByCatAndType()
      }
    },
    async getParamsByCatAndType() {
      const { data: res } = await this.$http.get(
        `categories/${this.threeCatId}/attributes`,
        { params: { sel: this.activeName } }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数信息失败！')
      }
      res.data.forEach((item, index) => {
        if (item.attr_vals.trim()) {
          res.data[index].attr_vals = item.attr_vals.split(' ')
        } else {
          res.data[index].attr_vals = []
        }
      })
      console.log(res)
      if (this.activeName === 'many') {
        this.paramsManyInfo = res.data
      } else {
        this.paramsOnlyInfo = res.data
      }
    }
  },
  computed: {
    isDisabled() {
      if (this.selectedPat.length === 3) {
        return false
      }
      return true
    }
    // 获取当前选中的第三级分类id
    // catId() {
    //   var len = this.selectedPat.length
    //   if (len === 3) {
    //     return this.selectedPat[len - 1]
    //   }
    //   return 0
    // }
  }
}
</script>

<style lang="less" scoped>
.box-card {
  margin-top: 15px;
}
.el-row {
  margin-top: 15px;
}
.el-table {
  margin-top: 15px;
  font-size: 12px;
}
.el-tag {
  margin: 10px 5px;
}
.el-input {
  width: 110px;
}
</style>
